from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import ListCreateAPIView, UpdateAPIView, RetrieveAPIView, ListAPIView
from rest_framework.response import Response

from apps.spit.models import Spit
from apps.spit.serializers import SpitListSerializer
from shicifang.utils.utils import PageNum


class SpitListView(ListCreateAPIView):
    queryset = Spit.objects.filter(parent_id__isnull=True)
    serializer_class = SpitListSerializer
    pagination_class = PageNum


class SpitCollectedView(UpdateAPIView):
    # 修改收藏状态
    queryset = Spit.objects.filter(parent_id__isnull=True)
    serializer_class = SpitListSerializer

    def update(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        try:
            spit = Spit.objects.get(pk=pk)
        except Spit.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        if spit.collected is True:
            spit.collected = False
        else:
            spit.collected = True
        spit.save()
        data = {'message': 'ok', 'success': True}
        return Response(data)


class SpitHasthumbupView(UpdateAPIView):
    # 是否点赞
    queryset = Spit.objects.filter(parent_id__isnull=True)
    serializer_class = SpitListSerializer

    def update(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        try:
            spit = Spit.objects.get(pk=pk)
        except Spit.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        if spit.hasthumbup is True:
            spit.hasthumbup = False
        else:
            spit.hasthumbup = True
        spit.save()
        data = {'message': 'ok', 'success': True}
        return Response(data)

class SpitView(RetrieveAPIView):
    queryset = Spit.objects.filter(parent_id__isnull=True)
    serializer_class = SpitListSerializer
    def retrieve(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        spit = Spit.objects.get(pk=pk)
        spit.visits += 1
        spit.save()
        serializer = self.get_serializer(spit)
        return Response(serializer.data)

class SpitCommentView(ListAPIView):
    serializer_class = SpitListSerializer
    def get_queryset(self):
        pk = self.kwargs.get('pk')
        return Spit.objects.filter(parent=pk)